package com.assets.Receive;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;

import android.text.TextUtils;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.assets.Allot.ReceivingDepartment;
import com.assets.Check.newTanWanCheck.BaseActivity1;
import com.assets.newNHF.util.LogUtils;
import com.assets.util.Since_case;
import com.assets.util.TrustAllCerts;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnDismissListener;
import com.bigkoo.alertview.OnItemClickListener;
import com.assets.Adapter.Receive_da;
import com.assets.Shift.Allot_department;
import com.assets.Shift.Allot_unit;
import com.assets.Ip_set.Url;
import com.assets.R;
import com.assets.CanniBalize.Shift_site;
import com.assets.bean.Receive_add_bean;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2019/1/3.
 */

public class Receive_add extends BaseActivity1 implements OnDismissListener {
    private String deptId = "", receive_dept_id = "";//部门id
    private TextView recipient_name;//领用名,管理人
    private String receivesUser;//领用id
    private String placeId = "", JSON;
    //                                    领用部门
    private TextView place, companyName, tv_receiving_department;
    private EditText et_remark;//备注
    private String url, add_url;
    private TextView deptName;//部门名字
    private String companyId = "";
    private ListView lv_list;
    List<Map<String, Object>> list_data = new ArrayList<Map<String, Object>>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.receive_add);
        //url = "http://" + Ip_Set.IP + "/api/receivesInspect";
        add_url = "http://" + Url.IP + "/api/receivesAdd";
        initView();
        //获取当前日期
    }

    private void initView() {
        companyName = (TextView) findViewById(R.id.fold);
        tv_receiving_department = findViewById(R.id.tv_receiving_department);
        lv_list = (ListView) findViewById(R.id.fragment2_list);
        Button add = (Button) findViewById(R.id.add);
        place = (TextView) findViewById(R.id.place);
        TextView tv_title = (TextView) findViewById(R.id.title_text);
        tv_title.setText("添加领用");
        ImageView fh = (ImageView) findViewById(R.id.fh);
        fh.setOnClickListener(v -> finish());
        et_remark = (EditText) findViewById(R.id.receive_remark);
        recipient_name = (TextView) findViewById(R.id.receive_recipient);
        deptName = (TextView) findViewById(R.id.receive_section);
        Button uploading = (Button) findViewById(R.id.upload);
        LinearLayout ll_company = (LinearLayout) findViewById(R.id.fold_unit);
        LinearLayout add_place = (LinearLayout) findViewById(R.id.add_place);
        LinearLayout ll_dept = (LinearLayout) findViewById(R.id.add_department);
        LinearLayout recipient_user = (LinearLayout) findViewById(R.id.add_recipient);
        LinearLayout ll_receiving_department = (LinearLayout) findViewById(R.id.ll_receiving_department);
        ll_company.setOnClickListener(v -> {//公司
            deptName.setText("");//事业部名字
            deptId = "";
            recipient_name.setText("");//领用人名字
            receivesUser = "";
            tv_receiving_department.setText("");//领用部门
            receive_dept_id = "";
            Intent dept = new Intent(this, Allot_unit.class);
            startActivityForResult(dept, 1);
        });
        ll_dept.setOnClickListener(v -> {//事业部
            if (TextUtils.isEmpty(companyId)) {
                showToast("请先选择公司");
                return;
            }
            if (!companyName.getText().toString().equals("")) {
                tv_receiving_department.setText("");//领用部门
                receive_dept_id = "";
                recipient_name.setText("");//领用人名字
                receivesUser = "";
                Intent intent = new Intent(this, Allot_department.class);
                intent.putExtra("department_id", companyId);
                startActivityForResult(intent, 2);
            }
        });
        ll_receiving_department.setOnClickListener(v -> {//领用部门
            if (TextUtils.isEmpty(deptId)) {
                showToast("请先选择事业部");
                return;
            }
            recipient_name.setText("");//领用人名字
            receivesUser = "";
            Intent intent = new Intent(this, ReceivingDepartment.class);
            intent.putExtra("deptId", deptId);
            startActivityForResult(intent, 4);
        });
        recipient_user.setOnClickListener(v -> {//领用人
            if (TextUtils.isEmpty(receive_dept_id)) {
                showToast("请先选择领用部门");
                return;
            }
            if (!deptName.getText().toString().equals("")) {
                Intent intent = new Intent(this, add_recipient.class);
                intent.putExtra("department_id", receive_dept_id);
                startActivityForResult(intent, 2);
            }
        });
        add_place.setOnClickListener(v -> {//存放地方
            Intent dept = new Intent(this, Shift_site.class);
            startActivityForResult(dept, 3);
        });
        uploading.setOnClickListener(v -> {//上传
            if (list_data.size() == 0) {
                showToast("请添加需要领用的资产");
                return;
            }
            if (TextUtils.isEmpty(companyId)) {
                showToast("请选择公司");
                return;
            }
            if (TextUtils.isEmpty(deptId)) {
                showToast("请选择事业部");
                return;
            }
            if (TextUtils.isEmpty(receive_dept_id)) {
                showToast("请选择领用部门");
                return;
            }
            if (TextUtils.isEmpty(receivesUser)) {
                showToast("请选择领用人");
                return;
            }
            if (TextUtils.isEmpty(placeId)) {
                showToast("请选择存放位置");
                return;
            }
            submit();
        });
        //添加
        add.setOnClickListener(v -> {
            if (list_data.size() > 0) {
                showToast("请提交领用后再添加资产");
                return;
            }
            /*if (TextUtils.isEmpty(companyId)) {
                showToast("请先选择公司");
                return;
            }*/
            Intent intent = new Intent(Receive_add.this, add_category.class);
            intent.putExtra("company_id", "companyId");
            startActivityForResult(intent, 6);
        });
    }

    private void submit() {
        String remarks = et_remark.getText().toString();
        RequestBody requestBody = new FormBody.Builder()
                .add("receivesDept", receive_dept_id)
                .add("receivesUser", receivesUser)
                .add("receivesRemark", remarks)
                .add("place", placeId)
                .add("company", companyId)
                .add("division", deptId)
                .add("createuser", Since_case.getInstance().getUserId())
                .add("receiveItems", JSON)
                .build();
        new Thread() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient
                            .Builder()
                            .hostnameVerifier(new AllowAllHostnameVerifier())
                            .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
                            .connectTimeout(10, TimeUnit.SECONDS)//连接超时
                            .readTimeout(500, TimeUnit.SECONDS)
                            .build();
                    Request request = new Request.Builder()
                            .url(add_url)
                            .post(requestBody).build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    LogUtils.d(responseData);
                    showResponse_load(responseData);//解析
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private void showResponse_load(final String responseData) {
        runOnUiThread(() -> {
            JSONObject js = null;
            try {
                js = new JSONObject(responseData);
                if (js.getString("state").equals("0")) {
                    showToast("提交失败");
                }
                if (js.getString("state").equals("1")) {
                    showToast("申请成功");
                    finish();
                }
                if (js.getString("state").equals("2")) {
                    new AlertView("申请添加成功", "是否继续添加", "取消", new String[]{"确定"}, null, Receive_add.this, AlertView.Style.Alert, new OnItemClickListener() {
                        @Override
                        public void onItemClick(Object o, int position) {
                            //取消：position=-1,确定 position=0
                            if (position == 0) {
                                //Toast.makeText(Receive_add.this,"申请添加成功",Toast.LENGTH_SHORT).show();
                              /*  category_name.setText("");
                                num.setText("");*/
                            }
                        }
                    }).setCancelable(true).setOnDismissListener(Receive_add.this).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //公司
        if (requestCode == 1 && resultCode == 1) {
            companyId = data.getExtras().getString("company_id");
            String name = data.getExtras().getString("company_name");
            companyName.setText(name);
        }
        //事业部
        if (requestCode == 2 && resultCode == 2) {
            deptId = data.getExtras().getString("dept_id");
            String name = data.getExtras().getString("dept_name");
            deptName.setText(name);
            LogUtils.d(deptId);
        }
        //领用部门
        if (requestCode == 4 && resultCode == 2) {
            receive_dept_id = data.getExtras().getString("dept_id");
            String name = data.getExtras().getString("dept_name");
            tv_receiving_department.setText(name);
            LogUtils.d(receive_dept_id + name);
        }

        if (requestCode == 2 && resultCode == 3) {
            recipient_name.setText(data.getExtras().getString("recipient_name"));
            receivesUser = data.getExtras().getString("recipient_id");
            LogUtils.d(data.getExtras().getString("recipient_name") + "id" + receivesUser);
        }
      /*  if (requestCode==3&&resultCode==3){
            category_name.setText(data.getExtras().getString("category_name"));
            category_id = data.getExtras().getString("category_id");
        }*/
        if (requestCode == 3 && resultCode == 3) {
            place.setText(data.getExtras().getString("site_name"));
            placeId = data.getExtras().getString("site_id");
        }
        if (requestCode == 6 && resultCode == 6) {
            JSON = data.getExtras().getString("list");
            Log.i("asdasdasd", data.getExtras().getString("list"));
            Gson gson = new Gson();
            List<Receive_add_bean> userList = gson.fromJson(data.getExtras().getString("list"), new TypeToken<List<Receive_add_bean>>() {
            }.getType());
            for (int i = 0; i < userList.size(); i++) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("coding_name", userList.get(i).getName());
                map.put("receivesDept_name", userList.get(i).getNum());
                map.put("receivesUser_name", userList.get(i).getUser());
                map.put("reapplyDate_name", userList.get(i).getPlace());
                list_data.add(map);
            }
            Receive_da receive_da = new Receive_da(Receive_add.this, list_data);
            lv_list.setAdapter(receive_da);
        }
    }

    @Override
    public void onDismiss(Object o) {

    }


}
